package com.xucan.serialialbel;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

class Container implements Serializable {
    private List<MyClass> list;

    public Container(List<MyClass> list) {
        this.list = list;
    }

    public List<MyClass> getList() {
        return list;
    }
}

class MyClass implements Serializable {
    private int value;

    public MyClass(int value) {
        this.value = value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }
}

public class Main {
    public static void main(String[] args) {
        // 创建多个对象
        MyClass obj1 = new MyClass(10);
        MyClass obj2 = new MyClass(20);

        // 修改对象属性
        obj1.setValue(30);
        obj2.setValue(40);

        // 创建一个容器集合
        List<MyClass> objList = new ArrayList<>();
        objList.add(obj1);
        objList.add(obj2);

        // 序列化容器
        Container container = new Container(objList);
        try (FileOutputStream fos = new FileOutputStream("data.ser");
             ObjectOutputStream oos = new ObjectOutputStream(fos)) {
            oos.writeObject(container);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 反序列化容器
        Container readContainer = null;
        try (FileInputStream fis = new FileInputStream("data.ser");
             ObjectInputStream ois = new ObjectInputStream(fis)) {
            readContainer = (Container) ois.readObject();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }

        // 输出容器中的对象
        List<MyClass> list = readContainer.getList();
        for (MyClass obj : list) {
            System.out.println("Obj value in container: " + obj.getValue());
        }
    }
}